/**
 * 
 */
package com.kylin.erp.oa.system.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.kylin.erp.dbmodel.TMenuResources;

/**
 * @author huxiang
 * 
 */
@Service
public class SystemMenuService {

	/**
	 * 获取用户可用的菜单，
	 * @param menuId为0的话，则是获取最顶级的
	 * @return
	 */
	public JSONArray getUserMenus(int menuId) {

		JSONArray ztreeNodes = new JSONArray();

		List<TMenuResources> topMenus = TMenuResources.dao.find(
				"select * from t_menu_resources where parent_id_ = ?",
				menuId);
		for (int i = 0; i < topMenus.size(); i++) {

			TMenuResources menu = topMenus.get(i);
			ztreeNodes.add(this.buildZtreeNode(menu));
		}

		return ztreeNodes;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private JSONObject buildZtreeNode(TMenuResources menu) {
		JSONObject ob = new JSONObject();
		ob.put("name", menu.getStr("name_"));
		Map userData = new HashMap();
		userData.put("link", menu.getStr("url_"));
		ob.put("userData", userData);
		ob.put("id", menu.getInt("id_"));
		List<TMenuResources> submenus = TMenuResources.dao.find(
				"select * from t_menu_resources where parent_id_ = ?",
				menu.getInt("id_"));
		JSONArray ja = new JSONArray();
		if (null != submenus && submenus.size() > 0) {
			for (int i = 0; i < submenus.size(); i++) {
				TMenuResources tmenu = submenus.get(i);
				ja.add(this.buildZtreeNode(tmenu));
			}
			ob.put("children", ja);
		} else {
			
		}
		return ob;
	}
}
